package com.zsc.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.oj.annotation.AuthCheck;
import com.zsc.oj.common.BaseResponse;
import com.zsc.oj.common.DeleteRequest;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.common.ResultUtils;
import com.zsc.oj.constant.UserConstant;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.exception.ThrowUtils;
import com.zsc.oj.model.dto.tbComment.TbCommentAddRequest;
import com.zsc.oj.model.dto.tbComment.TbCommentEditRequest;
import com.zsc.oj.model.dto.tbComment.TbCommentQueryRequest;
import com.zsc.oj.model.dto.tbComment.TbCommentUpdateRequest;
import com.zsc.oj.model.entity.TbComment;
import com.zsc.oj.model.entity.User;
import com.zsc.oj.model.vo.TbCommentVO;
import com.zsc.oj.service.TbCommentService;
import com.zsc.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 评论接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/tbComment")
@Slf4j
public class TbCommentController {

    @Resource
    private TbCommentService tbCommentService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建评论
     *
     * @param tbCommentAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTbComment(@RequestBody TbCommentAddRequest tbCommentAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(tbCommentAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        TbComment tbComment = new TbComment();
        BeanUtils.copyProperties(tbCommentAddRequest, tbComment);
        // 数据校验
        tbCommentService.validTbComment(tbComment, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        tbComment.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = tbCommentService.save(tbComment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newTbCommentId = tbComment.getId();
        return ResultUtils.success(newTbCommentId);
    }

    /**
     * 删除评论
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTbComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        TbComment oldTbComment = tbCommentService.getById(id);
        ThrowUtils.throwIf(oldTbComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldTbComment.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = tbCommentService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新评论（仅管理员可用）
     *
     * @param tbCommentUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTbComment(@RequestBody TbCommentUpdateRequest tbCommentUpdateRequest) {
        if (tbCommentUpdateRequest == null || tbCommentUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        TbComment tbComment = new TbComment();
        BeanUtils.copyProperties(tbCommentUpdateRequest, tbComment);
        // 数据校验
        tbCommentService.validTbComment(tbComment, false);
        // 判断是否存在
        long id = tbCommentUpdateRequest.getId();
        TbComment oldTbComment = tbCommentService.getById(id);
        ThrowUtils.throwIf(oldTbComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = tbCommentService.updateById(tbComment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取评论（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TbCommentVO> getTbCommentVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        TbComment tbComment = tbCommentService.getById(id);
        ThrowUtils.throwIf(tbComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(tbCommentService.getTbCommentVO(tbComment, request));
    }

    /**
     * 分页获取评论列表（仅管理员可用）
     *
     * @param tbCommentQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<TbComment>> listTbCommentByPage(@RequestBody TbCommentQueryRequest tbCommentQueryRequest) {
        long current = tbCommentQueryRequest.getCurrent();
        long size = tbCommentQueryRequest.getPageSize();
        // 查询数据库
        Page<TbComment> tbCommentPage = tbCommentService.page(new Page<>(current, size),
                tbCommentService.getQueryWrapper(tbCommentQueryRequest));
        return ResultUtils.success(tbCommentPage);
    }

    /**
     * 分页获取评论列表（封装类）
     *
     * @param tbCommentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TbCommentVO>> listTbCommentVOByPage(@RequestBody TbCommentQueryRequest tbCommentQueryRequest,
                                                               HttpServletRequest request) {
        long current = tbCommentQueryRequest.getCurrent();
        long size = tbCommentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<TbComment> tbCommentPage = tbCommentService.page(new Page<>(current, size),
                tbCommentService.getQueryWrapper(tbCommentQueryRequest));
        // 获取封装类
        return ResultUtils.success(tbCommentService.getTbCommentVOPage(tbCommentPage, request));
    }

    /**
     * 分页获取当前登录用户创建的评论列表
     *
     * @param tbCommentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<TbCommentVO>> listMyTbCommentVOByPage(@RequestBody TbCommentQueryRequest tbCommentQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(tbCommentQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        tbCommentQueryRequest.setUserId(loginUser.getId());
        long current = tbCommentQueryRequest.getCurrent();
        long size = tbCommentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<TbComment> tbCommentPage = tbCommentService.page(new Page<>(current, size),
                tbCommentService.getQueryWrapper(tbCommentQueryRequest));
        // 获取封装类
        return ResultUtils.success(tbCommentService.getTbCommentVOPage(tbCommentPage, request));
    }

    /**
     * 编辑评论（给用户使用）
     *
     * @param tbCommentEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editTbComment(@RequestBody TbCommentEditRequest tbCommentEditRequest, HttpServletRequest request) {
        if (tbCommentEditRequest == null || tbCommentEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        TbComment tbComment = new TbComment();
        BeanUtils.copyProperties(tbCommentEditRequest, tbComment);
        // 数据校验
        tbCommentService.validTbComment(tbComment, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = tbCommentEditRequest.getId();
        TbComment oldTbComment = tbCommentService.getById(id);
        ThrowUtils.throwIf(oldTbComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldTbComment.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = tbCommentService.updateById(tbComment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
